﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using iTextSharp.text;
using Microsoft.AspNetCore.Http;
using MySqlX.XDevAPI.Common;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.SportBusiness.Information;
using SportsPlatform.Dto.WeChat;
using SportsPlatform.Global;
using SportsPlatform.Helpers;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Query.WeChat;
using SportsPlatform.Redis;
using SportsPlatform.WeChat.IWeChat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SportsPlatform.WeChat.WeChat
{
    /// <summary>
    /// 移动端资讯服务接口实现
    /// </summary>
    [RemoteService(false)]
    public class NewsService : SportsPlatformAppServiceBase, INewsService
    {
        private readonly IRepository<Information, Guid> _repository;
        private readonly IRepository<CategoryNews, Guid> _categoryNewsRepository;
        private readonly IRedisRepository _redisRepository;
        public NewsService(IRepository<Information, Guid> repository, IRepository<CategoryNews, Guid> categoryNewsRepository, IHttpContextAccessor context,
            IRedisRepository redisRepository) : base(context)
        {
            _repository = repository;
            _categoryNewsRepository = categoryNewsRepository;
            _redisRepository = redisRepository;
        }

        /// <summary>
        /// 通过分类标识获取资讯列表
        /// </summary>
        /// <param name="query">传入参数</param>
        /// <returns></returns>
        public async Task<ResultListDto<GetByCategoryIdToNewsDto>> GetByCategoryIdToNews(WeChatGetCategoryQuery query)
        {
            ResultListDto<GetByCategoryIdToNewsDto> resultDto = new ResultListDto<GetByCategoryIdToNewsDto>();
            try
            {
                var list = new List<Information>();
                var listdto = new List<GetByCategoryIdToNewsDto>();
                var types = await _repository.GetAllListAsync(t => t.IsDeleted == false && t.IsEnable == true);
                if (query.Id == Guid.Empty || query.Id == null)
                {
                    list = types.OrderByDescending(o => o.CreateTime).ToList();
                    if (list.Count > 0)
                    {
                        foreach (var item in list)
                        {
                            var dto = new GetByCategoryIdToNewsDto();
                            dto.Id = item.Id;
                            dto.CreateTime = item.CreateTime.ToString("yyyy-MM-dd");
                            dto.Cover = item.Cover;
                            dto.ArticleTitle = item.ArticleTitle;
                            dto.ShareSummary = item.ShareSummary;
                            dto.ReadingCount = item.ReadingCount;
                            listdto.Add(dto);
                        }
                        resultDto.Data = listdto.ToPage(query.PageIndex, query.PageSize).ToList();
                        resultDto.Count = listdto.Count;
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.IsSuccess = true;
                        resultDto.Message = "获取成功";
                    }
                    else
                    {
                        resultDto.Code = HttpResultCode.NotData;
                        resultDto.Message = "未查询到数据";
                    }
                    return resultDto;
                }
                else
                {
                    var cns = await _categoryNewsRepository.GetAllListAsync(cn => cn.CategoryId == query.Id && cn.IsDeleted == false);
                    if (cns.Count > 0)
                    {
                        foreach (var item in cns)
                        {
                            var information = await _repository.GetAsync(item.NewsId);
                            if (information.IsNullAndEmpty())
                            {
                                resultDto.Code = HttpResultCode.NotData;
                                resultDto.IsSuccess = false;
                                resultDto.Message = "当前资讯不存在";
                                return resultDto;
                            }
                            list.Add(information);
                        }
                        list = list.Where(l => l.IsEnable == true && l.IsDeleted == false).OrderByDescending(l => l.CreateTime).ToList();
                    }

                    if (list.Count > 0)
                    {
                        list = list.Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize).ToList();
                        foreach (var item in list)
                        {
                            var dto = new GetByCategoryIdToNewsDto();
                            dto.Id = item.Id;
                            dto.CreateTime = item.CreateTime.ToString("yyyy-MM-dd");
                            dto.Cover = item.Cover;
                            dto.ArticleTitle = item.ArticleTitle;
                            dto.ShareSummary = item.ShareSummary;
                            dto.ReadingCount = item.ReadingCount;
                            listdto.Add(dto);
                        }

                        resultDto.Data = listdto;
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.IsSuccess = true;
                        resultDto.Message = "获取成功";
                    }
                    else
                    {
                        resultDto.Code = HttpResultCode.NotData;
                        resultDto.IsSuccess = false;
                        resultDto.Message = "未查询到数据";
                    }
                }
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 通过标识获取对象
        /// </summary>
        /// <param name="Id">资讯标识</param>
        /// <returns></returns>
        public async Task<ResultDto<GetInformationByIdDto>> GetInformationById(GetInformationByIdQuery query)
        {
            ResultDto<GetInformationByIdDto> resultDto = new ResultDto<GetInformationByIdDto>();
            var dto = new GetInformationByIdDto();
            try
            {
                var info = await _repository.FirstOrDefaultAsync(p => p.Id == query.Id);
                if (info != null)
                {
                    dto.ArticleContent = info.ArticleContent;
                    dto.CreateTime = info.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                    dto.ArticleTitle = info.ArticleTitle;
                    dto.ShareSummary = info.ShareSummary;
                    dto.Cover = info.Cover;
                    dto.Id = info.Id;

                    info.ReadingCount += 1;

                    try
                    {
                        await _repository.UpdateAsync(info);

                    }
                    catch (Exception)
                    {
                        UldLoggerContext.Error("更新资讯失败");
                    }

                    dto.ReadingCount = info.ReadingCount;
                    //获取不包含当前咨询的最新5条咨询
                    var recommed = _repository.GetAllList(p => p.IsEnable == true && p.IsDeleted == false).Where(x => x.Id != query.Id).OrderByDescending(x => x.CreateTime).Skip(0).Take(5).ToList();
                    var list = new List<RecommendInformation>();
                    if (recommed.Count > 0)
                    {
                        foreach (var item in recommed)
                        {
                            list.Add(new RecommendInformation()
                            {
                                Id = item.Id,
                                ArticleTitle = item.ArticleTitle,
                                Cover = item.Cover,
                                ReadingCount = item.ReadingCount,
                                CreateTime = item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")
                            });
                        }
                    }
                    dto.RecommendInformations = list;

                    resultDto.Code = HttpResultCode.Success;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "获取成功";
                    resultDto.Data = dto;
                }
                else
                {
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "未查询到数据";
                }
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }


        /// <summary>
        /// 获取所有资讯
        /// </summary>
        /// <returns></returns>
        public async Task<PagePagingDto<GetByCategoryIdToNewsDto>> GetInformationList(BasePageQuery query)
        {
            PagePagingDto<GetByCategoryIdToNewsDto> resultDto = new PagePagingDto<GetByCategoryIdToNewsDto>();
            try
            {
                var types = await _repository.GetAllListAsync(i => i.IsEnable == true && i.IsDeleted == false);
                if (types.Count > 0)
                {
                    var pages = types.Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize).ToList();
                    resultDto.Data = ObjectMapper.Map<List<GetByCategoryIdToNewsDto>>(types);
                    resultDto.TotalCount = types.Count;
                }
                resultDto.Code = types.Count > 0 ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = types.Count > 0;
                resultDto.Message = types.Count > 0 ? "获取成功" : "获取失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }
    }
}
